<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('attendance_records', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('employee_id')->comment('员工ID');
            $table->date('date')->comment('考勤日期');
            $table->time('check_in_time')->nullable()->comment('上班打卡时间');
            $table->time('check_out_time')->nullable()->comment('下班打卡时间');
            $table->decimal('work_hours', 5, 2)->default(0)->comment('工作时长');
            $table->enum('status', ['present', 'absent', 'late', 'early_leave', 'leave', 'overtime'])->default('present')->comment('考勤状态');
            $table->text('notes')->nullable()->comment('备注');
            $table->unsignedBigInteger('approved_by')->nullable()->comment('审批人ID');
            $table->timestamp('approved_at')->nullable()->comment('审批时间');
            $table->timestamps();

            // 外键约束
            $table->foreign('employee_id')->references('id')->on('employees')->onDelete('cascade');
            $table->foreign('approved_by')->references('id')->on('users')->onDelete('set null');

            // 索引
            $table->index(['employee_id', 'date']);
            $table->index(['date', 'status']);
            $table->index('status');

            // 唯一约束：每个员工每天只能有一条考勤记录
            $table->unique(['employee_id', 'date']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('attendance_records');
    }
};
